package juntos.lbcv;

import juntos.lbcv.interfaces.AppInterface.AppCallBackForAnnonce;
import juntos.lbcv.thread.CheckAlertTask;
import juntos.lbcv.thread.DetailAnnonceTask;
import juntos.lbcv.thread.ListAnnonceTask;
import juntos.lbcv.thread.SendingAlertTask;
import juntos.lbcv.utils.InstallRefTable;
import juntos.lbcv.utils.Lbc;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

public class App implements AppCallBackForAnnonce {


	private CheckAlertTask checkAlertTask;
	private SendingAlertTask sendingAlertTask;
	private ConfigurableApplicationContext context;
	private ThreadPoolTaskExecutor taskExecutor;
	private ListAnnonceTask listAnnonceTask;

	/**
	 * Create the application.
	 */
	public App() {
		initApplicationContext();
	}


	public void instertRefTable() {
		InstallRefTable refTabBean = context.getBean("installRefTable",
				InstallRefTable.class);
		//refTabBean.insertRegionDepartementFromSiteWeb();
	//	refTabBean.insertMarqueModeleFromLeBonCoin();

	}

	public void runApp(){

		taskExecutor.execute(listAnnonceTask);
	//	taskExecutor.execute(checkAlertTask);
	//	taskExecutor.execute(sendingAlertTask);

		for (;;) {
			int count = taskExecutor.getActiveCount();
			Lbc.waitXSecondes(300);
			if (count == 0) {
				taskExecutor.shutdown();
				break;
			}
		}
		
	}
	/**
	 * fonction la plus importante pour initialiser tout les beans et
	 * application context
	 */
	private void initApplicationContext() {
		this.context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		this.taskExecutor = (ThreadPoolTaskExecutor) context
				.getBean("taskExecutor");
		
		this.listAnnonceTask = (ListAnnonceTask) context.getBean("listAnnonceTask");
		this.sendingAlertTask = (SendingAlertTask) context.getBean("sendingAlertTask");
		this.checkAlertTask = (CheckAlertTask) context.getBean("checkAlertTask");
		this.listAnnonceTask.setAppCallBack(this);
	}
	
	
	@Override
	public DetailAnnonceTask getDetailAnnonceTask() {
		return (DetailAnnonceTask) context.getBean("detailAnnonceTask");
	}

	public void closeApplicationContext() {
		this.context.close();
	}

	/**
	 * Launch the application.
	 */
	public static void main(final String[] args) {
		
				try {
					App window = new App();
				//	window.frame.setVisible(true);
					Lbc.printOut("Start Application");
				//	window.instertRefTable();
					window.runApp();
					window.closeApplicationContext();
	
				} catch (Exception e) {
					e.printStackTrace();
			}
	}

	

}
